package com.wx.activitys.mayday.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.github.sd4324530.fastweixin.api.JsAPI;
import com.github.sd4324530.fastweixin.api.OauthAPI;
import com.github.sd4324530.fastweixin.api.enums.OauthScope;
import com.github.sd4324530.fastweixin.api.response.GetSignatureResponse;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.github.sd4324530.fastweixin.api.response.OauthGetTokenResponse;
import com.wx.activitys.base.controller.BaseController;

@Controller
@RequestMapping(value = "/mayday")
public class MayDayEnterController extends BaseController{
	@Autowired
	private OauthAPI authAPI;
	@Autowired
	private JsAPI jsAPI;
	
	public static final String ROOT_NAME="mayday";
	public static final String BASE_PATH="http://wxh5.xuanzhen-tech.com";
	//public static final String BASE_PATH="http://localhost:8080/wx_activity";
	public static final String BASE_URL=BASE_PATH+"/"+ROOT_NAME;
	public static final String REDIRECT_URL=BASE_URL+"/dealAuthUser.html";
	
	@RequestMapping(value = "auth2.html", method = RequestMethod.GET)
	public void auth2(HttpServletResponse response) throws IOException {
		//String redirectURL=authAPI.getOauthPageUrl2Hand(REDIRECT_URL,OauthScope.SNSAPI_USERINFO);
		String redirectURL=authAPI.getOauthPageUrl(REDIRECT_URL, OauthScope.SNSAPI_USERINFO, "STATE");
		System.out.println(redirectURL);
		response.sendRedirect(redirectURL);
	}
	@RequestMapping(value = "dealAuthUser.html", method = RequestMethod.GET)
	public String dealAuthUser(HttpSession session, HttpServletRequest request){
		String code = request.getParameter("code");
		OauthGetTokenResponse authToken = authAPI.getToken(code);
		GetUserInfoResponse userInfo = authAPI.getUserInfo(authToken.getAccessToken(), authToken.getOpenid());
		userInfo.setOpenid(authToken.getOpenid());
		logger.info("openid is "+authToken.getOpenid());
		logger.info("headImgUrl is "+userInfo.getHeadimgurl());
		logger.info("nickName is "+userInfo.getNickname());
		session.setAttribute("userInfo", userInfo);
		return ROOT_NAME+"/redirect";
	}
	
	@RequestMapping(value = "index.html", method = RequestMethod.GET)
	public String index(Model model, HttpServletRequest request){
		model.addAttribute("baseUrl", BASE_URL);
		String currentPage=BASE_URL+"/index.html";
		GetSignatureResponse signObj=jsAPI.getSignature(currentPage);
		model.addAttribute("signObj", signObj);
		model.addAttribute("basePath", BASE_PATH);
		return ROOT_NAME+"/index";
	}
}
